package com.hangxintong.common.exception;

import com.hangxintong.common.utils.Result;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 自定义异常处理器
 * @author lvyanfei
 * @date 2020-12-24
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Result handleBindException(MethodArgumentNotValidException ex) {
        FieldError fieldError = ex.getBindingResult().getFieldError();
        return Result.show(Integer.valueOf(fieldError.getCode()),fieldError.getDefaultMessage());
    }

//    @ExceptionHandler(value = GlobalException.class)
//    public Result exceptionHandler(GlobalException e){
//        return Result.msg(e.getMessage());
//    }
//
//    @ExceptionHandler(value = AbstractException.class)
//    public Result exceptionHandler(AbstractException e){
//        return Result.msg(e.getErrorCode(),e.getMessage());
//    }

    @ExceptionHandler(AbstractException.class)
    @ResponseBody
    public Result runtimeException(AbstractException e) {
        e.printStackTrace();
        return Result.show(e.getErrorCode(),e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result exception(Exception e) {
        e.printStackTrace();
        return Result.show(SystemErrorCodeMark.Code.SYS_0001.getErrorCode(),e.getMessage());
    }

}
